package org.jeecg.gen;

import com.google.gson.Gson;
import org.jeecg.device.util.DeviceInfo;
import org.jeecg.device.util.DeviceUtil;
import org.jeecg.gen.util.KeyUtil;
import lombok.extern.slf4j.Slf4j;
import org.jeecg.tool.MyLicenseCreator;
import org.jeecg.tool.bean.LicenseCreatorParam;
import org.springframework.util.FileCopyUtils;

import java.io.*;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;

/**
 * @Author jeecg
 * @Description
 * @Date 2022/6/15 14:47
 */
@Slf4j
public class MainApp {
    public static void main(String[] args) {
        Map<String, String> params = new HashMap<>();
        //先读取配置文件
        String os = System.getProperty("os.name");
        File config = null;
        File outDir = null;
        if (os != null && os.toLowerCase().startsWith("linux")) {
            String currentDir = null;
            for (String arg : args) {
                String[] split = arg.trim().split("=");
                if (split.length == 2) {
                    if (split[0].equals("currentDir")) {
                        currentDir = split[1];
                        break;
                    }
                }
            }
            if (currentDir == null) {
                throw new RuntimeException("请执行Linux脚本");
            }

            config = new File(currentDir + "/config/config.properties");
            outDir = new File(currentDir + "/out");
        } else if (os != null && os.toLowerCase().startsWith("windows")) {
            String path = MainApp.class.getClassLoader().getResource("application.properties").getPath();
            config = new File(path);
            outDir = new File("./out");
        }
        if (config != null && config.exists()) {
            try {
                InputStream inputStream = new BufferedInputStream(new FileInputStream(config));
                Properties properties = new Properties();
                properties.load(inputStream);
                String property = properties.getProperty("license.subject");
                if (property != null && !property.trim().equals("")) {
                    params.put("subject", property.trim());
                }
                property = properties.getProperty("license.storePass");
                if (property != null && !property.trim().equals("")) {
                    params.put("storePass", property.trim());
                }
                property = properties.getProperty("license.privatePass");
                if (property != null && !property.trim().equals("")) {
                    params.put("privatePass", property.trim());
                }
                property = properties.getProperty("license.licenseRoot");
                if (property != null && !property.trim().equals("")) {
                    params.put("licenseRoot", property.trim());
                }
                property = properties.getProperty("license.timeout");
                if (property != null && !property.trim().equals("")) {
                    params.put("timeout", property.trim());
                }
            } catch (FileNotFoundException e) {
                throw new RuntimeException(e);
            } catch (IOException e) {
                throw new RuntimeException(e);
            }

        }
        for (String arg : args) {
            String[] split = arg.trim().split("=");
            if (split.length != 2) {
                throw new RuntimeException("参数异常!");
            }
            params.put(split[0], split[1]);
        }
        log.info("获取参数：" + params.toString());
        if (!params.containsKey("subject") || !params.containsKey("storePass") || !params.containsKey("privatePass")
                || !params.containsKey("timeout") || !params.containsKey("licenseRoot")) {
            throw new RuntimeException("必要参数缺失！");
        }
        String subject = params.get("subject");
        String pubPwd = params.get("storePass");
        String priPwd = params.get("privatePass");
        String licenseRoot = params.get("licenseRoot");
        String timeout = params.get("timeout");

        if (!outDir.exists()) {
            outDir.mkdirs();
        }

        try {
            //生成公私钥对
            log.info("----------开始执行证书生成----------------");
            KeyUtil.createKey(subject, pubPwd, priPwd, outDir.getCanonicalPath());

            //读取客户端设备信息
            DeviceInfo deviceInfo = DeviceUtil.getDeviceInfo();
            String json = new Gson().toJson(deviceInfo);
            //过期时间
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd+HH:mm:ss");
            Date outTime = sdf.parse(timeout);
            //生成license
            LicenseCreatorParam param = new LicenseCreatorParam()
                    .setSubject(subject)
                    .setPubPass(pubPwd)
                    .setPriPass(priPwd)
                    .setDeviceInfo(json)
                    .setExpiryTime(outTime)
                    .setPriKeyPath(outDir.getCanonicalPath() + File.separator + "private.key")
                    .setLicensePath(outDir.getCanonicalPath() + File.separator + "license.lic");
            new MyLicenseCreator()
                    .setCreatorParam(param)
                    .execute();
            log.info("----------证书生成完毕----------------");
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            throw new RuntimeException("证书生成失败！");
        }
        try {
            log.info("----------将文件拷贝到文件夹[" + licenseRoot + "]----------------");
            File rootDir = new File(licenseRoot);
            if (!rootDir.exists()) {
                rootDir.mkdirs();
            }
            File fileIn1 = new File(outDir.getCanonicalPath() + File.separator + "license.lic");
            File fileOut1 = new File(rootDir.getAbsolutePath() + File.separator + "license.lic");
            if (!fileOut1.exists()) {
                fileOut1.createNewFile();
            }
            FileCopyUtils.copy(fileIn1, fileOut1);

            File fileIn2 = new File(outDir.getCanonicalPath() + File.separator + "public.key");
            File fileOut2 = new File(rootDir.getAbsolutePath() + File.separator + "public.key");
            if (!fileOut2.exists()) {
                fileOut2.createNewFile();
            }
            FileCopyUtils.copy(fileIn2, fileOut2);
            log.info("---------成功！！！--------------");
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            throw new RuntimeException("拷贝文件失败，可以将out文件夹里的文件手动拷贝到目标文件夹！");
        }
    }
}
